/**
 *  Copyright (c) 2010-2011, Monash e-Research Centre
 * (Monash University, Australia)
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 * * Neither the name of the Monash University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/**
 * Grischa and Steve's awesome confluence plugin!!!
 * 
 */
package au.edu.monash.its.confluence.plugins;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.atlassian.confluence.core.ConfluenceActionSupport;
import com.atlassian.confluence.labels.LabelManager;
import com.atlassian.confluence.pages.AbstractPage;
import com.atlassian.confluence.pages.Attachment;
import com.atlassian.confluence.pages.actions.PageAware;
import com.atlassian.confluence.setup.settings.Settings;
import com.atlassian.confluence.setup.settings.SettingsManager;
import com.atlassian.confluence.user.AuthenticatedUserThreadLocal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author grischa, steve
 * 
 */
public class FedoraPublish extends ConfluenceActionSupport implements PageAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3637226113108157623L;
	private AbstractPage page;
	private String pid;
	private String baseURL;
	private String errorMessage;
	private String xmlreply;
	private String debug;
	private String xmlrequest;

	public String getXmlrequest() {
		return xmlrequest;
	}

	public void setXmlrequest(String xmlrequest) {
		this.xmlrequest = xmlrequest;
	}
	
	public String getDebug() {
		return debug;
	}

	public void setDebug(String debug) {
		this.debug = debug;
	}	

	public String getXmlreply() {
		return xmlreply;
	}

	public void setXmlreply(String xmlreply) {
		this.xmlreply = xmlreply;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getBaseURL() {
		return baseURL;
	}

	public void setBaseURL(String baseURL) {
		this.baseURL = baseURL;
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	private FedoraPublishManager fedoraPublishManager;

	/**
	 * Implementation of PageAware
	 */
	public AbstractPage getPage() {
		return page;
	}

	/**
	 * Implementation of PageAware
	 */
	public void setPage(AbstractPage page) {
		this.page = page;
	}

	/**
	 * Implementation of PageAware: Returning 'true' ensures that the page is
	 * set before the action commences.
	 */
	public boolean isPageRequired() {
		return true;
	}

	/**
	 * Implementation of PageAware: Returning 'true' ensures that the current
	 * version of the page is used.
	 */
	public boolean isLatestVersionRequired() {
		return true;
	}

	/**
	 * Implementation of PageAware: Returning 'true' ensures that the user
	 * requires page view permissions.
	 */
	public boolean isViewPermissionRequired() {
		return true;
	}

	/**
	 * Dependency-injection of the Confluence LabelManager.
	 */
	public void setLabelManager(LabelManager labelManager) {
		this.labelManager = labelManager;
	}

	public String convertStreamToString(InputStream is) throws IOException {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {
			return "";
		}
	}
	
	public void setSettingsManager(SettingsManager settingsManager)
	{
	    this.settingsManager = settingsManager;
	}	

	public String execute() {
		errorMessage = "Error publishing to ARROW: Is the confluence page public?";
		xmlreply = "No reply from server.";
		try {
			final Logger LOG = LoggerFactory.getLogger("atlassian.plugin");
			
			//LOG.error("Something bad happened");
			//LOG.debug("Information useful during development");
			//LOG.info("Information you wish your plugin administrators to view");
			
			Settings globalSettings = settingsManager.getGlobalSettings();
			String serverURL = globalSettings.getBaseUrl();
			baseURL = fedoraPublishManager.getServerURL();
	
			boolean authorisedUser = false;
			String loggedInUser = AuthenticatedUserThreadLocal.getUsername();
			LOG.debug("logged in as: " + loggedInUser);
			// kill execution if user not in list
			for (String user : fedoraPublishManager.getPublishUsers().split(",")) {
				if (user.trim().equals(loggedInUser)) {
					authorisedUser = true;
				}
			}
	
			if (!authorisedUser) {
				return "unauthorised";
			}
	
			boolean attachedDc = false;
			String dcFileString = null;
	
			// TODO: Need to get these from confluence page:
			String objName = page.getTitle();
			String fileDescription = page.getTitle() + " PDF Export";
			String creatorName = page.getCreatorName();
	
			// no idea what this field is for. mime type?
			String objType = "";
	
			// maybe just set this to objName ?
			String fileName = "";
	
			FedoraUploader fedUp;
			try {
				
				fedUp = new FedoraUploader(new URL(fedoraPublishManager
						.getServerURL()), fedoraPublishManager.getUsername(),
						fedoraPublishManager.getPassword());
	
				for (Attachment attachment : page.getAttachments()) {
					if (attachment.getFileName().equals("dc.xml")) {
						try {
							dcFileString = convertStreamToString(attachment
									.getContentsAsStream());
							attachedDc = true;
							LOG.debug(dcFileString);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							errorMessage = "Problem uploading dublin core xml";
							e.printStackTrace();
						}
					}
	
				}
				String encodedFoxml = null;
				if (attachedDc) {
					encodedFoxml = createFoxML(objName, fileName, fileDescription,
							creatorName, objType, dcFileString);
				} else {
					encodedFoxml = createFoxML(objName, fileName, fileDescription,
							creatorName, objType);
				}
				String pidRequest = createPIDRequestString(objName, encodedFoxml);
				String xmlWithPID = "";
				//xmlrequest = pidRequest;
				xmlrequest = "";
				try {
					xmlWithPID = PostSoapXML.postXMLSoapRequest(new URL(
							fedoraPublishManager.getServerURL()),
							fedoraPublishManager.getUsername(),
							fedoraPublishManager.getPassword(), pidRequest);
				} catch (MalformedURLException e) {
					errorMessage = e.getMessage();
					e.printStackTrace();
					return "error";
				} catch (Exception e) {
					errorMessage = e.getMessage();
					e.printStackTrace();
					return "error";
				}
				// System.out.println(xmlWithPID);
				String PID = "";
				xmlreply = xmlWithPID;
				if (xmlWithPID != "") {
					LOG.debug(xmlWithPID);
					PID = extractPID(xmlWithPID);
					LOG.debug(PID);
					this.setPid(PID);
				} else {
					LOG.error("xmlWithPID error");
					return "error";
				}
				String fileURL = null;
				Integer dsidcount = 0;
				for (Attachment attachment : page.getAttachments()) {
	
					if (attachment.getFileName().equals("MODS.xml")) {
						try {
							String modsFileString = convertStreamToString(attachment
									.getContentsAsStream());
							LOG.debug("MODS: " + modsFileString);
	
							fileURL = fedUp.uploadFile(copyInputStreamToTmpFile(
									attachment.getContentsAsStream(), "MODS", "."
											+ attachment.getFileExtension()));
	
							String datastreamXML = registerXMLstring(attachment
									.getFileName(), "MODS", "MODS Descriptive Metadata",
									PID, fileURL, "I");
							// String datastreamXML =
							// registerFileXMLstring(attachment.getFileName(),
							// attachment.getComment(), PID, fileURL,
							// "application/octet-stream");
							LOG.debug(datastreamXML);
	
							String fedResponse = PostSoapXML.postXMLSoapRequest(
									new URL(fedoraPublishManager.getServerURL()),
									fedoraPublishManager.getUsername(),
									fedoraPublishManager.getPassword(),
									datastreamXML);
							LOG.debug("uploaded.. " + fedResponse);
						} catch (IOException e) {
							errorMessage = "Problem uploading mods xml";
							LOG.error(e.getMessage());
							e.printStackTrace();
						}
						// } else if (attachment.getFileName().equals("dc.xml")) {
						// try {
						// String modsFileString =
						// convertStreamToString(attachment.getContentsAsStream());
						// System.out.println("DC: " + modsFileString);
						//
						// fileURL =
						// fedUp.uploadFile(copyInputStreamToTmpFile(attachment.getContentsAsStream(),
						// "." + attachment.getFileExtension()));
						//
						// String datastreamXML =
						// registerXMLstring(attachment.getFileName(), "DC",
						// "Default Dublin Core Record", PID, fileURL);
						// // String datastreamXML =
						// registerFileXMLstring(attachment.getFileName(),
						// attachment.getComment(), PID, fileURL,
						// // "application/octet-stream");
						// System.out.println(datastreamXML);
						//
						// String fedResponse = PostSoapXML.postXMLSoapRequest(new
						// URL(fedoraPublishManager.getServerURL()),
						// fedoraPublishManager.getUsername(),
						// fedoraPublishManager.getPassword(), datastreamXML);
						//
						// System.out.println("uploaded.. " + fedResponse);
						// } catch (IOException e) {
						// // TODO Auto-generated catch block
						// e.printStackTrace();
						// }
	
					} else {
						if (!attachment.getFileName().equals("dc.xml")) {
							fileURL = fedUp.uploadFile(copyInputStreamToTmpFile(
									attachment.getContentsAsStream(), "dc", "."
											+ attachment.getFileExtension()));
							// TODO more smartness here!
							String dsid = null;
							String mimetype = null;
							String label;
							if (!attachment.getFileExtension().equals("mp3")) {
								dsidcount++;
								dsid = "DOC" + dsidcount.toString();
								label = "Transcript";
								if (attachment.getFileExtension().equals("pdf"))
									mimetype = "application/pdf";
								else
									mimetype = "application/msword";
							} else {
								dsid = "AUDIO";
								label = "Media";
								mimetype = "audio/x-mp3";
							}
							String datastreamXML = registerFileXMLstring(label, //attachment.getFileName(), 
									dsid, label, // attachment.getComment(),
									PID, fileURL, mimetype, "M");
							LOG.debug(datastreamXML);
							String fedResponse = PostSoapXML.postXMLSoapRequest(
									new URL(fedoraPublishManager.getServerURL()),
									fedoraPublishManager.getUsername(),
									fedoraPublishManager.getPassword(),
									datastreamXML);
	
							// System.out.println("uploaded.. " + fedResponse);
						}
					}
				}
	
				// /spaces/flyingpdf/pdfpageexport.action?pageId=
				
				File pdfFile = PDFcreator.getPDF(new URL(globalSettings.getBaseUrl()), page
						.getIdAsString(), fedoraPublishManager.getPDFUser(),
						fedoraPublishManager.getPDFPassword());
				if (pdfFile != null) {
					fileURL = fedUp.uploadFile(pdfFile);
					LOG.debug(fileURL);
				} else {
					LOG.error("pdf file was not uploaded");
					return "error";
				}
	
				dsidcount++;
				String dsid = "DOC" + dsidcount.toString();
				String mimetype = "application/pdf";
				String datastreamXML = registerFileXMLstring("Transcript", dsid,
						"Transcript", PID, fileURL, mimetype, "M");
				LOG.debug(datastreamXML);
	
				String fedResponse = PostSoapXML.postXMLSoapRequest(new URL(
						fedoraPublishManager.getServerURL()), fedoraPublishManager
						.getUsername(), fedoraPublishManager.getPassword(),
						datastreamXML);
				LOG.debug(fedResponse);
	
				String relsext = "";
	
				//<foxml:datastream ID="RELS-EXT" STATE="A" CONTROL_GROUP="X" VERSIONABLE="true">
				//<foxml:datastreamVersion ID="RELS-EXT.0" LABEL="RDF" CREATED="2011-05-24T06:00:50.981Z" MIMETYPE="text/xml" SIZE="296">
				//<foxml:xmlContent>
				relsext = "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" ";
				relsext += "xmlns:rel=\"info:fedora/fedora-system:def/relations-external#\">\n";
				relsext += "  <rdf:Description rdf:about=\"info:fedora/" + PID + "\">\n";
				relsext += "    <rel:isMemberOf rdf:resource=\"info:fedora/monash:62979\"></rel:isMemberOf>\n";
				relsext += "  </rdf:Description>\n";
				relsext += "</rdf:RDF>";
				//</foxml:xmlContent>
	
				fileURL = fedUp
						.uploadFile(copyInputStreamToTmpFile(new ByteArrayInputStream(relsext.getBytes()), "rels-ext", ".xml"));
	
				String relsDatastreamXML = registerXMLstring("rels-ext.xml",
						"RELS-EXT", "Relationship Metadata", PID, fileURL, "A");
				
				fedResponse = PostSoapXML.postXMLSoapRequest(new URL(
						fedoraPublishManager.getServerURL()), fedoraPublishManager
						.getUsername(), fedoraPublishManager.getPassword(),
						relsDatastreamXML);
	
				LOG.debug("uploaded.. " + fedResponse);
	
			} catch (MalformedURLException e1) {
				errorMessage = "Fedora URL incorrect. Please contact a system administrator.";
				e1.printStackTrace();
				return "error";
			} catch (Exception e1) {
				xmlrequest = "";
				errorMessage = "Error publishing to ARROW: Is the confluence page public?";
				e1.printStackTrace();
				return "error";
			}
		} catch (Exception e1) {
			// dumb, catch-all!
			xmlrequest = "";
			e1.printStackTrace();
			return "error";
		}

		return "success";
	}

	private String registerFileXMLstring(String objName, String dsid,
			String fileDescription, String PID, String fileURL, String mimetype, String controlGroup) {
		String datastreamXML = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
				+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
				+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soap:Body>"
				+ "<ns1:addDatastream"
				+ " xmlns:ns1=\"http://api._0._1.definitions.www.fedora.info\">"
				+ "<ns1:in0>"
				+ PID
				+ "</ns1:in0> <ns1:in1>"
				+ dsid
				+ "</ns1:in1> <ns1:in2/>"
				+ "<ns1:in3>"
				+ objName
				+ "</ns1:in3> <ns1:in4>true</ns1:in4>"
				+ "<ns1:in5>"
				+ mimetype
				+ "</ns1:in5> <ns1:in6></ns1:in6>"
				+ "<ns1:in7>"
				+ fileURL
				+ "</ns1:in7> <ns1:in8>" + controlGroup + "</ns1:in8>"
				+ "<ns1:in9>A</ns1:in9> <ns1:in10 xsi:nil=\"true\"/> <ns1:in11"
				+ " xsi:nil=\"true\"/> <ns1:in12>"
				+ fileDescription
				+ "</ns1:in12>"
				+ "</ns1:addDatastream> </soap:Body> </soap:Envelope>";
		return datastreamXML;
	}

	private String registerXMLstring(String objName, String dsid,
			String fileDescription, String PID, String fileURL, String state) {
		String datastreamXML = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
				+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
				+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soap:Body>"
				+ "<ns1:addDatastream"
				+ " xmlns:ns1=\"http://api._0._1.definitions.www.fedora.info\">"
				+ "<ns1:in0>"
				+ PID
				+ "</ns1:in0> <ns1:in1>"
				+ dsid
				+ "</ns1:in1> <ns1:in2/>"
				+ "<ns1:in3>"
				+ fileDescription
				+ "</ns1:in3> <ns1:in4>true</ns1:in4>"
				+ "<ns1:in5>text/xml</ns1:in5> <ns1:in6></ns1:in6>"
				+ "<ns1:in7>"
				+ fileURL
				+ "</ns1:in7> <ns1:in8>X</ns1:in8>"
				+ "<ns1:in9>" + state + "</ns1:in9> <ns1:in10 xsi:nil=\"true\"/> <ns1:in11"
				+ " xsi:nil=\"true\"/> <ns1:in12>"
				+ fileDescription
				+ "</ns1:in12>"
				+ "</ns1:addDatastream> </soap:Body> </soap:Envelope>";
		return datastreamXML;
	}

	private String extractPID(String xmlWithPID) {
		Pattern pattern = Pattern.compile("<objectPID.+>(.+)<\\/objectPID>");
		Matcher matcher = pattern.matcher(xmlWithPID);

		matcher.find();
		String PID = matcher.group().split(">")[1].split("<")[0];

		return PID;
	}

	private String createPIDRequestString(String objName, String foxml) {
		String pidRequest = "";
		pidRequest = pidRequest + "<soap:Envelope xmlns:soap=\"http://schema";
		pidRequest = pidRequest + "s.xmlsoap.org/soap/envelope/\" xmlns:xsd=";
		pidRequest = pidRequest + "\"http://www.w3.org/2001/XMLSchema\" xmln";
		pidRequest = pidRequest + "s:xsi=\"http://www.w3.org/2001/XMLSchema-";
		pidRequest = pidRequest + "instance\"><soap:Body><ns1:ingest xmlns:n";
		pidRequest = pidRequest + "s1=\"http://api._0._1.definitions.www.fed";
		pidRequest = pidRequest + "ora.info\"><ns1:in0>";
		pidRequest = pidRequest + foxml;
		pidRequest = pidRequest + "</ns1:in0><ns1:in1>info:fedora/fedora-system:FOXML-1.1</ns1:in1><ns1";
		pidRequest = pidRequest + ":in2>" + objName
				+ "</ns1:in2></ns1:ingest></";
		pidRequest = pidRequest + "soap:Body></soap:Envelope>";
		return pidRequest;
	}

	private String createFoxML(String objName, String fileName,
			String fileDescription, String creatorName, String objType) {
		String foxml = "";
		foxml = foxml + "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <foxml:d";
		foxml = foxml + "igitalObject VERSION=\"1.1\" xmlns:foxml=\"info:fedora/fedora-syste";
		foxml = foxml + "m:def/foxml#\" xmlns:xsi=\"http://www.w3.org/2001/X";
		foxml = foxml + "MLSchema-instance\" xsi:schemaLocation=\"info:fedor";
		foxml = foxml + "a/fedora-system:def/foxml# http://www.fedora.info/d";
		foxml = foxml + "efinitions/1/0/foxml1-1.xsd\"><foxml:objectProperties><f";
		foxml = foxml + "oxml:property NAME=\"info:fedora/fedora-system:def/";
		foxml = foxml + "model#state\" VALUE=\"A\"/><foxml:property NAME=\"i";
		foxml = foxml + "nfo:fedora/fedora-system:def/model#label\" VALUE=\"";
		foxml = foxml + objName + "\"/><foxml:extproperty NAME=\"info:fedora/f";
		foxml = foxml + "edora-system:def/model#contentModel\" VALUE=\"";
		foxml = foxml + fileName;
		foxml = foxml + "\"/>";
		foxml = foxml + "<foxml:extproperty NAME=\"http://www.w3.org/1999";
		foxml = foxml + "/02/22-rdf-syntax-ns#type\" VALUE=\"FedoraObject\"/></foxml:objectProperties><foxml:datastream";
		foxml = foxml + " ID=\"DC\" STATE=\"A\" CONTROL_GROUP=\"X\"><foxml:d";
		foxml = foxml + "atastreamVersion ID=\"DC.0\" MIMETYPE=\"text/xml\" ";
		foxml = foxml + "LABEL=\"Dublin Core\"><foxml:xmlCont";
		foxml = foxml + "ent><oai_dc:dc xmlns:oai_dc=\"http://www.openarchiv";
		foxml = foxml + "es.org/OAI/2.0/oai_dc/\" xmlns:dc=\"http://purl.org";
		foxml = foxml + "/dc/elements/1.1/\"><dc:title>" + objName;
		foxml = foxml + "</dc:title";
		foxml = foxml + "><dc:description>" + fileDescription + "</dc:descript";
		foxml = foxml + "ion><dc:creator>" + creatorName + "</dc:creator><dc:t";
		foxml = foxml + "ype>" + objType + "</dc:type></oai_dc:dc> </foxml:";
		foxml = foxml + "xmlContent></foxml:datastreamVersion></foxml:datast";
		foxml = foxml + "ream></foxml:digitalObject>";
		try {
			foxml = PostSoapXML.encode(foxml.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e1) {
			errorMessage = "FOXML encoding error. Please contact a system administrator.";
			e1.printStackTrace();
			return "error";
		} catch (Exception e1) {
			errorMessage = "Error publishing to ARROW: Is the confluence page public?";
			e1.printStackTrace();
			return "error";
		}
		return foxml;
	}

	private String createFoxML(String objName, String fileName,
			String fileDescription, String creatorName, String objType,
			String dcFileString) {
		String foxml = "";
		foxml = foxml + "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <foxml:d";
		foxml = foxml + "igitalObject VERSION=\"1.1\" xmlns:foxml=\"info:fedora/fedora-syste";
		foxml = foxml + "m:def/foxml#\" xmlns:xsi=\"http://www.w3.org/2001/X";
		foxml = foxml + "MLSchema-instance\" xsi:schemaLocation=\"info:fedor";
		foxml = foxml + "a/fedora-system:def/foxml# http://www.fedora.info/d";
		foxml = foxml + "efinitions/1/0/foxml1-1.xsd\"><foxml:objectProperti";
		foxml = foxml + "es><f";
		foxml = foxml + "oxml:property NAME=\"info:fedora/fedora-system:def/";
		foxml = foxml + "model#state\" VALUE=\"A\"/><foxml:property NAME=\"i";
		foxml = foxml + "nfo:fedora/fedora-system:def/model#label\" VALUE=\"";
		foxml = foxml + objName + "\"/><foxml:extproperty NAME=\"info:fedora/f";
		foxml = foxml + "edora-system:def/model#contentModel\" VALUE=\"";
		foxml = foxml + fileName;
		foxml = foxml + "\"/><foxml:extproperty NAME=\"http://www.w3.org/1999";
		foxml = foxml + "/02/22-rdf-syntax-ns#type\" VALUE=\"FedoraObject\"/></foxml:objectProperties><foxml:datastream";
		foxml = foxml + " ID=\"DC\" STATE=\"A\" CONTROL_GROUP=\"X\"><foxml:d";
		foxml = foxml + "atastreamVersion ID=\"DC.0\" MIMETYPE=\"text/xml\" ";
		foxml = foxml + "LABEL=\"Dublin Core\"><foxml:xmlCont";
		foxml = foxml + "ent>" + dcFileString + "</foxml:";
		foxml = foxml + "xmlContent></foxml:datastreamVersion></foxml:datast";
		foxml = foxml + "ream></foxml:digitalObject>";
		try {
			foxml = PostSoapXML.encode(foxml.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e1) {
			errorMessage = "FOXML encoding error. Please contact a system administrator.";
			return "error";
		} catch (Exception e1) {
			e1.printStackTrace();
			errorMessage = "Error publishing to ARROW: Is the confluence page public?";
		}
		return foxml;
	}

	public static File copyInputStreamToTmpFile(InputStream input, String basename, String suffix)
			throws IOException {
		DataOutputStream output = null;
		File file = null;
		try {
			file = File.createTempFile(basename + "fedoraPublishtempfile", suffix);
			file.deleteOnExit();
			output = new DataOutputStream(new BufferedOutputStream(
					new FileOutputStream(file)));

			int c;
			while ((c = input.read()) != -1) {
				output.writeByte(c);
			}
			input.close();
			output.close();
			// copyInputStreamToOutput(input, output);
			// output.flush();
		} catch (Exception e) {
			
		}
		return file;
	}

	/**
	 * Like a single-threaded Pipe--copies from an InputStream to an
	 * OutputStream
	 * 
	 * @param input
	 * @param output
	 * @throws IOException
	 */
	public static void copyInputStreamToOutput(InputStream input,
			OutputStream output) throws IOException {
		output = new BufferedOutputStream(output);
		byte[] buffer = new byte[8096];
		int size;
		while ((size = input.read(buffer)) != -1) {
			output.write(buffer, 0, size);
		}
	}

	/**
	 * @param fedoraPublishManager
	 *            the fedoraPublishManager to set
	 */
	public void setFedoraPublishManager(
			FedoraPublishManager fedoraPublishManager) {
		this.fedoraPublishManager = fedoraPublishManager;
	}

}
